/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "EaseConversationListViewController.h"

#import "EaseEmotionEscape.h"
#import "EaseConversationCell.h"
#import "EaseConvertToCommonEmoticonsHelper.h"
#import "EaseMessageViewController.h"
#import "NSDate+Category.h"
#import "EaseLocalDefine.h"

@interface EaseConversationListViewController ()

@property (nonatomic ,strong) NSArray     * imgArry;
@property (nonatomic ,strong) NSArray     * nameArry;
@end

@implementation EaseConversationListViewController

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"home_nav_bg"] forBarMetrics:UIBarMetricsDefault];
    [super viewWillAppear:animated];
    [self tableViewDidTriggerHeaderRefresh];
    [self registerNotifications];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self unregisterNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorColor=SeparatorColor;
    self.tableView.separatorInset=UIEdgeInsetsZero;
    self.imgArry=[NSArray arrayWithObjects:@"icon_logistics",@"icon_inform",@"icon_customer_service", nil];
    self.nameArry=[NSArray arrayWithObjects:@"订单消息",@"通知",@"客服人员", nil];
    [self tableViewDidTriggerHeaderRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
//    if (section==0) {
//        return 3;
//    }else{
       return [self.dataArray count];
  //  }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.section==0) {
//        static NSString *CellIdentifier = @"Cell";
//        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        if (cell == nil) {
//            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//        }
//        cell.imageView.image=[UIImage imageNamed:self.imgArry[indexPath.row]];
//        cell.textLabel.text=self.nameArry[indexPath.row];
//        return cell;
//    }else{
        NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
        EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        // Configure the cell...
        if (cell == nil) {
            cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        
        if ([self.dataArray count] <= indexPath.row) {
            return cell;
        }
        
        id<IConversationModel> model = [self.dataArray objectAtIndex:indexPath.row];
        cell.model = model;
        
        if (_dataSource && [_dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTitleForConversationModel:)]) {
            NSMutableAttributedString *attributedText = [[_dataSource conversationListViewController:self latestMessageTitleForConversationModel:model] mutableCopy];
            [attributedText addAttributes:@{NSFontAttributeName : cell.detailLabel.font} range:NSMakeRange(0, attributedText.length)];
            cell.detailLabel.attributedText =  attributedText;
        } else {
            cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:[self _latestMessageTitleForConversationModel:model]textFont:cell.detailLabel.font];
        }
        
        if (_dataSource && [_dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTimeForConversationModel:)]) {
            cell.timeLabel.text = [_dataSource conversationListViewController:self latestMessageTimeForConversationModel:model];
        } else {
            cell.timeLabel.text = [self _latestMessageTimeForConversationModel:model];
        }
        if ([model.conversation.conversationId isEqualToString:@"order_helper"]) {
            cell.avatarView.imageView.image=[UIImage imageNamed:@"msg_logistics"];
            cell.titleLabel.text=@"订单助手";
        }else if ([model.conversation.conversationId isEqualToString:@"aftersales"]){
            cell.avatarView.imageView.image=[UIImage imageNamed:@"msg_after_sales"];
            cell.titleLabel.text=@"售后消息";
        }else if ([model.conversation.conversationId isEqualToString:@"logi"]){
            cell.avatarView.imageView.image=[UIImage imageNamed:@"msg_customer_service"];
            cell.titleLabel.text=@"平台客服";
        }else if ([model.conversation.conversationId isEqualToString:@"info"]){
            cell.avatarView.imageView.image=[UIImage imageNamed:@"msg_inform"];
            cell.titleLabel.text=@"通知";
        }else if ([model.conversation.conversationId isEqualToString:@"wallet_helper"]){
            cell.avatarView.imageView.image=[UIImage imageNamed:@"msg_wallet"];
            cell.titleLabel.text=@"钱包助手";
        }else{
            if ([model.conversation.latestMessage.from isEqualToString:[ZJUserDefaultsTools getCurrentIMName]]) {
                [cell.avatarView.imageView sd_setImageWithURL:[NSURL URLWithString:[ZJUserDefaultsTools getAvatar]]];
                cell.titleLabel.text=[ZJUserDefaultsTools getCurrentNickName];
            }
        }
    cell.detailLabelFont=[UIFont systemFontOfSize:12];
    cell.titleLabel.font=[UIFont systemFontOfSize:14];
    cell.avatarView.imageView.backgroundColor=[UIColor clearColor];
        return cell;
 
    }
//}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [EaseConversationCell cellHeightWithModel:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    if (indexPath.section==0) {
//        EaseMessageViewController *viewController = [[EaseMessageViewController alloc] initWithConversationChatter:@"logistics" conversationType:EMConversationTypeChat];
//        viewController.title = @"logistics";
//        [self.navigationController pushViewController:viewController animated:YES];
//    }else{
        if (_delegate && [_delegate respondsToSelector:@selector(conversationListViewController:didSelectConversationModel:)]) {
            EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
            [_delegate conversationListViewController:self didSelectConversationModel:model];
        } else {
            EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
            EaseMessageViewController *viewController = [[EaseMessageViewController alloc] initWithConversationChatter:model.conversation.conversationId conversationType:model.conversation.type];
            if ([model.title isEqualToString:@"order_helper"]) {
                viewController.title = @"订单助手";
            }else if ([model.title isEqualToString:@"aftersales"]) {
                viewController.title = @"售后通知";
            }else if ([model.title isEqualToString:@"logi"]) {
                viewController.title = @"客服";
            }else if ([model.title isEqualToString:@"info"]) {
                viewController.title = @"通知";
            }else if ([model.title isEqualToString:@"wallet_helper"]) {
                viewController.title = @"钱包助手";
            }else {
                if ([model.title intValue]==1) {
                    viewController.title = @"紫金莲";
                }else{
                    viewController.title = model.title;
                }
                
            }
            
            [self.navigationController pushViewController:viewController animated:YES];
        }
 
    }
//}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row>3) {
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
        [[EMClient sharedClient].chatManager deleteConversation:model.conversation.conversationId isDeleteMessages:YES completion:nil];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

#pragma mark - data

-(void)refreshAndSortView
{
    if ([self.dataArray count] > 1) {
        if ([[self.dataArray objectAtIndex:0] isKindOfClass:[EaseConversationModel class]]) {
            NSArray* sorted = [self.dataArray sortedArrayUsingComparator:
                               ^(EaseConversationModel *obj1, EaseConversationModel* obj2){
                                   EMMessage *message1 = [obj1.conversation latestMessage];
                                   EMMessage *message2 = [obj2.conversation latestMessage];
                                   if(message1.timestamp > message2.timestamp) {
                                       return(NSComparisonResult)NSOrderedAscending;
                                   }else {
                                       return(NSComparisonResult)NSOrderedDescending;
                                   }
                               }];
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:sorted];
        }
    }
    [self.tableView reloadData];
}

/*!
 @method
 @brief 加载会话列表
 @discussion
 @result
 */
- (void)tableViewDidTriggerHeaderRefresh
{
    [self.dataArray removeAllObjects];
    EMConversation *ation0=[[EMClient sharedClient].chatManager getConversation:@"order_helper" type:EMConversationTypeChat createIfNotExist:YES];
    EaseConversationModel *model0 = [[EaseConversationModel alloc] initWithConversation:ation0];
    [self.dataArray insertObject:model0 atIndex:0];
    
    EMConversation *ation1=[[EMClient sharedClient].chatManager getConversation:@"aftersales" type:EMConversationTypeChat createIfNotExist:YES];
    EaseConversationModel *model1 = [[EaseConversationModel alloc] initWithConversation:ation1];
    [self.dataArray insertObject:model1 atIndex:1];
    EMConversation *ation2=[[EMClient sharedClient].chatManager getConversation:@"logi" type:EMConversationTypeChat createIfNotExist:YES];
    EaseConversationModel *model2 = [[EaseConversationModel alloc] initWithConversation:ation2];
    [self.dataArray insertObject:model2 atIndex:2];
    EMConversation *ation3=[[EMClient sharedClient].chatManager getConversation:@"info" type:EMConversationTypeChat createIfNotExist:YES];
    EaseConversationModel *model3 = [[EaseConversationModel alloc] initWithConversation:ation3];
    [self.dataArray insertObject:model3 atIndex:3];
    
    EMConversation *ation4=[[EMClient sharedClient].chatManager getConversation:@"wallet_helper" type:EMConversationTypeChat createIfNotExist:YES];
    EaseConversationModel *model4 = [[EaseConversationModel alloc] initWithConversation:ation4];
    [self.dataArray insertObject:model4 atIndex:4];
    
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSArray* sorted = [conversations sortedArrayUsingComparator:
                       ^(EMConversation *obj1, EMConversation* obj2){
                           EMMessage *message1 = [obj1 latestMessage];
                           EMMessage *message2 = [obj2 latestMessage];
                           if(message1.timestamp > message2.timestamp) {
                               return(NSComparisonResult)NSOrderedAscending;
                           }else {
                               return(NSComparisonResult)NSOrderedDescending;
                           }
                       }];
    for (EMConversation *converstion in sorted) {
        EaseConversationModel *model = nil;
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(conversationListViewController:modelForConversation:)]) {
            model = [self.dataSource conversationListViewController:self
                                                   modelForConversation:converstion];
        }
        else{
            model = [[EaseConversationModel alloc] initWithConversation:converstion];
        }
        
        if ([model.conversation.conversationId isEqualToString:@"order_helper"]) {
            [self.dataArray replaceObjectAtIndex:0 withObject:model];
        }else if ([model.conversation.conversationId isEqualToString:@"aftersales"]){
            [self.dataArray replaceObjectAtIndex:1 withObject:model];
        }else if ([model.conversation.conversationId isEqualToString:@"logi"]){
             [self.dataArray replaceObjectAtIndex:2 withObject:model];
        }else if ([model.conversation.conversationId isEqualToString:@"info"]){
             [self.dataArray replaceObjectAtIndex:3 withObject:model];
        }else if ([model.conversation.conversationId isEqualToString:@"wallet_helper"]){
            [self.dataArray replaceObjectAtIndex:4 withObject:model];
        }else {
            [self.dataArray addObject:model];
        }
    }
    
    [self.tableView reloadData];
    [self tableViewDidFinishTriggerHeader:YES reload:NO];
}

#pragma mark - EMGroupManagerDelegate

- (void)didUpdateGroupList:(NSArray *)groupList
{
    [self tableViewDidTriggerHeaderRefresh];
}
- (void)messagesDidRead:(NSArray *)aMessages{
    
}
-(void)messagesDidReceive:(NSArray *)aMessages{
    [self tableViewDidTriggerHeaderRefresh];
}
#pragma mark - registerNotifications
-(void)registerNotifications{
    [self unregisterNotifications];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
    [[EMClient sharedClient].chatManager removeDelegate:self];
    [[EMClient sharedClient].groupManager removeDelegate:self];
}

- (void)dealloc{
    [self unregisterNotifications];
}

#pragma mark - private

/*!
 @method
 @brief 获取会话最近一条消息内容提示
 @discussion
 @param conversationModel  会话model
 @result 返回传入会话model最近一条消息提示
 */
- (NSString *)_latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTitle = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSEaseLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSEaseLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSEaseLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSEaseLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSEaseLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}

/*!
 @method
 @brief 获取会话最近一条消息时间
 @discussion
 @param conversationModel  会话model
 @result 返回传入会话model最近一条消息时间
 */
- (NSString *)_latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        double timeInterval = lastMessage.timestamp ;
        if(timeInterval > 140000000000) {
            timeInterval = timeInterval / 1000;
        }
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        latestMessageTime = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
    }
    return latestMessageTime;
}

@end
